<template>
  <div>
    <a-card class="card" title="机构信息" :bordered="false">
      <organization-form ref="organization" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="服务行业" :bordered="false">
      <servindustry-form ref="servindustry" :showSubmit="false" />
    </a-card>
    <a-card class="card"  title="建设类型" :bordered="false">
      <servsysbuild-form :operateTye="1" ref="servsysbuild" :showSubmit="false" />
    </a-card>
    <a-card class="card"  title="运营类型" :bordered="false">
      <servsysbuild-form :operateTye="2" ref="servsysoper" :showSubmit="false" />
    </a-card>
    <a-card class="card"  title="实施类型" :bordered="false">
      <servsysbuild-form :operateTye="3" ref="regRealNalmp" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="许可证" :bordered="false">
      <licencelist-form2 ref="licencelist2" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="标识注册数据所在地/云服务商" :bordered="false">
      <idregdatalist-form ref="idregdatalist" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="标识注册系统所在地/云服务商" :bordered="false">
      <idregdatalist-form ref="idregsyslist" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="标识服务系统备份所在地/云服务商" :bordered="false">
      <idregdatalist-form ref="idsysbacklist" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="注册数据备份所在地/云服务商" :bordered="false">
      <idregdatalist-form ref="regdatabacklist" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="解析服务器所在地/云服务商" :bordered="false">
      <idregdatalist-form ref="regservlist" :showSubmit="false" />
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar v-if="type !== 'view'" :is-mobile="isMobile" :collapsed="sideCollapsed">
      <span class="popover-wrapper">
        <a-popover title="表单校验信息" overlayClassName="antd-pro-pages-forms-style-errorPopover" trigger="click" :getPopupContainer="trigger => trigger.parentNode">
          <template slot="content">
            <li v-for="item in errors" :key="item.key" @click="scrollToField(item.key)" class="antd-pro-pages-forms-style-errorListItem">
              <a-icon type="cross-circle-o" class="antd-pro-pages-forms-style-errorIcon" />
              <div class="">{{ item.message }}</div>
              <div class="antd-pro-pages-forms-style-errorField">{{ item.fieldLabel }}</div>
            </li>
          </template>
          <span class="antd-pro-pages-forms-style-errorIcon" v-if="errors.length > 0">
            <a-icon type="exclamation-circle" />{{ errors.length }}
          </span>
        </a-popover>
      </span>
      <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
  import OrganizationForm from './OrganizationForm'
  import IdregdatalistForm from './IdregdatalistForm'
  // import LicencelistForm from './LicencelistForm'
  import LicencelistForm2 from './LicencelistForm2'
  import ServsysbuildForm from './ServsysbuildForm'
  import ServindustryForm from './ServindustryForm'
  import FooterToolBar from '@/components/FooterToolbar'
  import { baseMixin } from '@/store/app-mixin'
  import {saveOrganizationInfo, editOrganizationInfo} from '@/api/organization'

  const fieldLabels = {
    gnrlId: '机构ID',
    orgName: '单位名称',
    orgNature: '单位性质',
    prefix: '标识前缀或范围',
  }

  export default {
    name: 'index',
    mixins: [baseMixin],
    components: {
      FooterToolBar,
      OrganizationForm,
      IdregdatalistForm,
      // LicencelistForm,
      LicencelistForm2,
      ServsysbuildForm,
      ServindustryForm
    },
    data () {
      return {
        type: '',
        loading: false,
        memberLoading: false,
        operate: {},
        errors: []
      }
    },
    activated() {
      if (this.$route.params) {
        const {type} = this.$route.params;
        this.type = type
        this.$refs.organization.getDetail(this.$route.params);
        this.$refs.servindustry.getDetail(this.$route.params);
        this.$refs.servsysbuild.getDetail(this.$route.params, 1);
        this.$refs.servsysoper.getDetail(this.$route.params, 2);
        this.$refs.regRealNalmp.getDetail(this.$route.params, 3);
        // this.$refs.licencelist.getDetail(this.$route.params);
        this.$refs.licencelist2.getDetail(this.$route.params);
        this.$refs.idregdatalist.getDetail(this.$route.params, 1);
        this.$refs.idregsyslist.getDetail(this.$route.params, 2);
        this.$refs.idsysbacklist.getDetail(this.$route.params, 3);
        this.$refs.regdatabacklist.getDetail(this.$route.params, 4);
        this.$refs.regservlist.getDetail(this.$route.params, 5);
      }
    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()
      },

      // 最终全页面提交
      validate () {
        // let a = '[{"institutionsOrganizationTb":{"gnrlid":"asd","orgname":"zzz","orgnature":2,"idregnalmp":"zzz","orgaddrprovinceId":9309,"orgaddrcityId":9321,"orgaddrcountyId":9323,"orgaddr":"zzz","orgcrttype":1,"orgcrtcode":"zzz","legalname":"zzz","legalcrttype":2,"legalcrtno":"zzz","orgdesc":"zzz","industrycategory":1,"industryspecific":2,"contactName":"zz","contactphone":"11111111111","contactcrttype":3,"contactcrtno":"11111","contactemail":"123@qq.com"}},{"institutionsServindustryTb":{"category":1,"specific":2,"trade":4,"subclass":7}},{"institutionsServsysbuildTb":{"biudtype":2,"entrorg":"22221"}},{"institutionsServsysoperTb":{"biudtype":2,"entrorg":"22221"}},{"institutionsRegRealNalmpTb":{"biudtype":2,"entrorg":"22221"}},{"institutionsLicencelistTb":{"licencetype":1,"licenceno":"22222"}},{"institutionsIdregdatalistTbs":[{"key":"1","name":"3333","address":"","editable":false,"isNew":false,"deploymode":"2"},{"key":"2","name":"","address":"22222","editable":false,"isNew":false,"deploymode":"1","province":"安徽","provinceId":9309,"city":"蚌埠","cityId":9321,"county":"怀远县","countyId":9322}]},{"institutionsIdregsyslistTbs":[{"key":"1","name":"2222","address":"","editable":false,"isNew":false,"deploymode":"2"},{"key":"2","name":"","address":"21212","editable":false,"isNew":false,"deploymode":"1","province":"甘肃","provinceId":9527,"city":"兰州","cityId":9528,"county":"城关区","countyId":9530}]},{"institutionsIdsysbacklistTbs":[{"key":"1","name":"11212","address":"","editable":false,"isNew":false,"deploymode":"2"},{"key":"2","name":"","address":"33","editable":false,"isNew":false,"deploymode":"1","province":"甘肃","provinceId":9527,"city":"白银","cityId":9537,"county":"平川区","countyId":9539}]},{"institutionsRegdatabacklistTbs":[{"key":"1","name":"21313","address":"","editable":false,"isNew":false,"deploymode":"2"},{"key":"2","name":"","address":"311313","editable":false,"isNew":false,"deploymode":"1","province":"广东","provinceId":9632,"city":"潮州","cityId":9655,"county":"潮安区","countyId":9657}]},{"institutionsRegservlistTbs":[{"key":"1","name":"213213","address":"","editable":false,"isNew":false,"deploymode":"2"},{"key":"2","name":"","address":"12312312","editable":false,"isNew":false,"deploymode":"1","province":"海南","provinceId":10042,"city":"海口","cityId":10043,"county":"龙华区","countyId":10045}]}]';
        // const rusult = {}
        // JSON.parse(a).forEach(value => {
        //   for (const k of Object.keys(value)) {
        //     rusult[k] = value[k]
        //   }
        // })
        // console.log(rusult)
        // saveOrganizationInfo(rusult).then(res =>{
        //   this.$notification['info']({
        //     message: '保存成功:',
        //     description: '成功'
        //   })
        // })
        // return
        const _this = this
        const {$refs: {organization, servindustry, servsysbuild, servsysoper, regRealNalmp, idregdatalist, idregsyslist,
          idsysbacklist, regdatabacklist, regservlist, licencelist2}, $notification} = this;
        const organizationForm = new Promise((resolve, reject) => {
          organization.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            values['id'] = organization.id
            resolve({institutionsOrganizationTb:values})
          })
        })
        const servindustryForm = new Promise((resolve, reject) => {
          servindustry.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            values['id'] = servindustry.id
            resolve({institutionsServindustryTb:values})
          })
        })
        const servsysbuildForm = new Promise((resolve, reject) => {
          servsysbuild.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            values['id'] = servsysbuild.id
            resolve({institutionsServsysbuildTb:values})
          })
        })
        const servsysoperForm = new Promise((resolve, reject) => {
          servsysoper.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            values['id'] = servsysoper.id
            resolve({institutionsServsysoperTb:values})
          })
        })
        const regRealNalmpForm = new Promise((resolve, reject) => {
          regRealNalmp.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            values['id'] = regRealNalmp.id
            resolve({institutionsRegRealNalmpTb:values})
          })
        })
        // const licencelistForm = new Promise((resolve, reject) => {
        //   licencelist.form.validateFields((err, values) => {
        //     if (err) {
        //       reject(err)
        //       return
        //     }
        //     values['id'] = licencelist.id
        //     resolve({institutionsLicencelistTb:values})
        //   })
        // })
        // clean this.errors
        this.errors = []
        let promiseList = [];
        promiseList.push(organizationForm)
        promiseList.push(servindustryForm)
        promiseList.push(servsysbuildForm)
        promiseList.push(servsysoperForm)
        promiseList.push(regRealNalmpForm)
        // promiseList.push(licencelistForm)
        if (idregdatalist.data && idregdatalist.data.length > 0) {
          if (idregdatalist.data.length <= 20) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsIdregdatalistTbs:idregdatalist.data})}));
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '标识注册数据所在地/云服务商，最多添加20组'
            })
            return
          }
        }
        if (idregsyslist.data && idregsyslist.data.length > 0) {
          if (idregsyslist.data.length <= 20) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsIdregsyslistTbs:idregsyslist.data})}))
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '标识注册系统所在地/云服务商，最多添加20组'
            })
            return
          }
        }
        if (idsysbacklist.data && idsysbacklist.data.length > 0) {
          if (idsysbacklist.data.length <= 20) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsIdsysbacklistTbs:idsysbacklist.data})}))
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '标识服务系统备份所在地/云服务商，最多添加20组'
            })
            return
          }
        }
        if (regdatabacklist.data && regdatabacklist.data.length > 0) {
          if (regdatabacklist.data.length <= 20) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsRegdatabacklistTbs:regdatabacklist.data})}))
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '注册数据备份所在地/云服务商，最多添加20组'
            })
            return
          }
        }
        if (regservlist.data && regservlist.data.length > 0) {
          if (regservlist.data.length <= 20) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsRegservlistTbs:regservlist.data})}))
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '解析服务器所在地/云服务商，最多添加20组'
            })
            return
          }
        }
        if (licencelist2.data && licencelist2.data.length > 0) {
          if (licencelist2.data.length <= 5) {
            promiseList.push(new Promise((resolve, reject) => {resolve({institutionsLicencelistTbs:licencelist2.data})}))
          } else {
            $notification['error']({
              message: '提交失败:',
              description: '许可证最多添加5组'
            })
            return
          }
        }
        Promise.all(promiseList).then(values => {
          console.log(JSON.stringify(values))
          const rusult = {}
          values.forEach(value => {
            for (const k of Object.keys(value)) {
              rusult[k] = value[k]
            }
          })
          console.log(rusult)
          if (this.type === 'edit') {
            editOrganizationInfo(rusult).then(res => {
              $notification['info']({
                message: '编辑成功:',
                description: '成功'
              })
              _this.$router.push({path:"/organization"})
            }).catch(res => {
              if (res.response) {
                $notification['error']({
                  message: res.response.data.message
                })
              }
            })
          } else {
            saveOrganizationInfo(rusult).then(res =>{
              $notification['info']({
                message: '保存成功:',
                description: '成功'
              })
              _this.$router.push({path:"/organization"})
            }).catch(res => {
              if (res.response) {
                $notification['error']({
                  message: res.response.data.message
                })
              }
            })
          }
        }).catch((e) => {
          const errors = Object.assign({},
            organization.form.getFieldsError(),
            servindustry.form.getFieldsError(),
            servsysbuild.form.getFieldsError(),
            servsysoper.form.getFieldsError(),
            // licencelist.form.getFieldsError(),
            regRealNalmp.form.getFieldsError())
          const tmp = { ...errors }
          this.errorList(tmp)
        })
      },
      errorList (errors) {
        if (!errors || errors.length === 0) {
          return
        }
        this.errors = Object.keys(errors)
          .filter(key => errors[key])
          .map(key => ({
            key: key,
            message: errors[key][0],
            fieldLabel: fieldLabels[key]
          }))
      },
      scrollToField (fieldKey) {
        const labelNode = document.querySelector(`label[for="${fieldKey}"]`)
        if (labelNode) {
          labelNode.scrollIntoView(true)
        }
      },
      close() {
        this.visible = false
        this.$emit('close')
      }
    }
  }
</script>

<style lang="less" scoped>
  .card{
    margin-bottom: 24px;
  }
  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }
  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;
    i {
      margin-right: 4px;
    }
  }
  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }
    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }
    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0,0,0,.45);
      font-size: 12px;
    }
  }
</style>
